import os,shutil
from PIL import Image, ImageDraw, ImageFont
import os

def expand_image_with_text(image_path, text, expand_height=180, font_size=150):
    """Expand the bottom of an image and add a bold text annotation."""
    image = Image.open(image_path)
    width, height = image.size
    new_height = height + expand_height  # Increase space for better text visibility

    # Create new image with extra space at the bottom
    expanded_image = Image.new("RGB", (width, new_height), (255, 255, 255))
    expanded_image.paste(image, (0, 0))

    # Draw text annotation
    draw = ImageDraw.Draw(expanded_image)

    # Try loading a font, fallback to default
    try:
        font = ImageFont.truetype("msyhbd.ttc", font_size)
    except:
        font = ImageFont.load_default()

    # Calculate text position
    bbox = draw.textbbox((0, 0), text, font=font)  # Get text bounding box
    text_width = bbox[2] - bbox[0]
    text_height = bbox[3] - bbox[1]
    text_x = (width - text_width) // 2
    text_y = height + (expand_height - text_height) // 2

    draw.text((text_x, text_y), text, fill=(0, 0, 0), font=font)

    return expanded_image

def make_final_image_square(image, final_size=2000, padding=50):
    """Expands image to make it a perfect square and resizes it to final_size (2000x2000)."""
    width, height = image.size
    new_size = max(width, height) + 2 * padding  # Ensure padding around edges
    square_image = Image.new("RGB", (new_size, new_size), (255, 255, 255))
    
    # Center the original image in the square canvas
    x_offset = (new_size - width) // 2
    y_offset = (new_size - height) // 2
    square_image.paste(image, (x_offset, y_offset))

    # Resize to final output size (2000x2000)
    resized_image = square_image.resize((final_size, final_size), Image.LANCZOS)
    return resized_image

def combine_images_with_title(image1_path, image2_path, output_path):
    """Combines two images horizontally with a title at the top, ensuring a 2000x2000px square output."""
    # Expand both images with labels ("Front" & "Back" text size now fully visible)
    expanded_image1 = expand_image_with_text(image1_path, "正面", font_size=120)
    expanded_image2 = expand_image_with_text(image2_path, "背面", font_size=120)

    # Ensure both images have the same height
    height = max(expanded_image1.height, expanded_image2.height)
    expanded_image1 = expanded_image1.resize((expanded_image1.width, height))
    expanded_image2 = expanded_image2.resize((expanded_image2.width, height))

    # Add spacing between the two images
    separator_width = 50
    combined_width = expanded_image1.width + expanded_image2.width + separator_width
    title_space = 250  # Space for title to fit 200px text
    gap_between_title_and_images = 150  # Ensure 120px gap
    combined_height = height + title_space + gap_between_title_and_images  # Extra space for title + gap

    # Create final image
    result_image = Image.new("RGB", (combined_width, combined_height), (255, 255, 255))

    # Paste expanded images with spacing in between
    result_image.paste(expanded_image1, (0, title_space + gap_between_title_and_images))
    result_image.paste(expanded_image2, (expanded_image1.width + separator_width, title_space + gap_between_title_and_images))

    # Draw "RESULT" title at the top
    draw = ImageDraw.Draw(result_image)
    
    try:
        font = ImageFont.truetype("msyhbd.ttc", 160)  # "RESULT" text size 200px
    except:
        font = ImageFont.load_default()

    # Get text bounding box for "RESULT"
    text = os.path.basename(output_path)
    bbox = draw.textbbox((0, 0), text, font=font)  
    text_width = bbox[2] - bbox[0]
    text_height = bbox[3] - bbox[1]
    text_x = (combined_width - text_width) // 2
    text_y = (title_space - text_height) // 2  # Center text in title space

    draw.text((text_x, text_y), text, fill=(0, 0, 0), font=font)

    # Ensure the final image is a perfect square and resized to 2000x2000 pixels
    final_square_image = make_final_image_square(result_image, final_size=2000)

    # Save final image
    final_square_image.save(output_path)
    print(f"✅ Final image saved as {output_path} (2000x2000 pixels)")


# combine_images_with_title("front.jpg", "back.jpg", "8DT80491-黑白灰12.jpg")




def get_paths(directory):
    paths = []
    for file in os.listdir(directory):
        path=os.path.join(directory,file)
        if os.path.isdir(path):
            path=path.replace('\\','/')
            paths.append(path)
    return paths



def pic_operate(directory):
    paths = get_paths(directory)

    for path in paths:
        if path.split('/')[-1]=='错误':
            continue
        files=os.listdir(path)
        correct_dict=['1.jpg', '2.jpg']
        if sorted(files)==sorted(correct_dict):
            path_front=os.path.join(path,'1.jpg')
            path_back=os.path.join(path,'2.jpg')
            pic_result=path.split('/')[-1]+'.jpg'
            path_result=os.path.join(path,pic_result)
            combine_images_with_title(path_front,path_back,path_result)
        else:
            print(path,"格式错误")
            dir_old=directory+'/'+path.split('/')[-1]
            dir_new=directory+'/'+'错误'
            if not os.path.exists(dir_new):
                os.makedirs(dir_new)
            shutil.move(dir_old,dir_new)